<?php
namespace app\api\controller;

use think\Db;
use think\Controller;
use think\Request;
use app\superadmin\model\Images;
use app\superadmin\model\Service;
use app\superadmin\model\City;
use app\superadmin\model\Car;
use app\superadmin\model\Order;
use app\superadmin\model\User;
use app\superadmin\model\Report;
use app\superadmin\model\Check;
use app\superadmin\model\Abnormal;
use app\superadmin\model\ReportList;


class Index extends controller
{   
	protected $img_text = ['左前45°','右前45°','左后45°','右后45°','车铭牌','中控台','表显里程','前排座椅','后排座椅','行李箱舱','发动机舱','机盖螺栓','左前叶子板螺栓','右前叶子板螺栓','前横梁螺栓','水箱框架螺栓','左前纵梁','右前纵梁','左前减震器座','右前减震器座','左A柱','左B柱','左C柱','左前门螺栓','左后门螺栓','右A柱','右B柱','右C柱','右前门螺栓','右后门螺栓','尾盖螺栓','后横梁螺栓','后围板焊点','尾箱底板与后围板交界','左后导水槽','右后导水槽','左后纵梁','右后纵梁','左前地板','右前地板','主驾座椅底部','副驾座椅底部','方向盘管柱','刹车踏板','左后地板','右后地板','备胎槽','其他'];
    //图片列表
    public function imagesList(){
    
       $oid = $this->request->param('oid');

       $info = Images::where('id',1)->find();

       $info['banner'] = json_decode($info['banner']);

       if ($oid) {
           
           $orderinfo = Db::table('yup_order')->where('id',$oid)->find();

           if ($orderinfo['staff_id']) {
                
                $info['zhang'] = Db::table('yup_user')->where('id',$orderinfo['staff_id'])->find()['zhang'];

           }
       }

       echo json_encode(array('status'=>1,'data'=>$info));
     
    }




    //服务项目列表
    public function serviceList(){

       $info = Service::order('px')->select();
   
       echo json_encode(array('status'=>1,'data'=>$info));
     
    }

    //获取省级列表
    public function provinceList(){
         
         $info = Db::name('city')->where('CRI_DATA_STATE',1)->field(['CRI_CODE'=>'value','CRI_NAME'=>'label','CRI_SUPERIOR_CODE'=>'pid'])->order('CRI_SORT')->select();

         $arr = $this->getTree($info);

         //halt($arr);
         echo json_encode(array('status'=>1,'data'=>$arr));

    }


    public function getTree($items,$pid ="pid") {
        $map  = [];
        $tree = [];
        foreach ($items as &$it){ $map[$it['value']] = &$it; }  //数据的ID名生成新的引用索引树
        foreach ($items as &$at){
            $parent = &$map[$at[$pid]];
            if($parent) {
                $parent['children'][] = &$at;
            }else{
                $tree[] = &$at;
                //$parent['children'] = [];
            }
        }
        return $tree;
    }

    // //获取市级列表
    // public function cityList(){
        
    //      $pid = $this->request->param('pid');

    //      $info = City::where('CRI_LEVEL',2)->where('CRI_SUPERIOR_CODE',$pid)->where('CRI_DATA_STATE',1)->field(['CRI_CODE'=>'value','CRI_NAME'=>'label'])->order('CRI_SORT')->select();

    //      echo json_encode(array('status'=>1,'data'=>$info));

    // }



    //  //获取县级列表
    // public function countyList(){
        
    //      $pid = $this->request->param('pid');

    //      $info = City::where('CRI_LEVEL',3)->where('CRI_SUPERIOR_CODE',$pid)->where('CRI_DATA_STATE',1)->field(['CRI_CODE'=>'value','CRI_NAME'=>'label'])->order('CRI_SORT')->select();

    //      echo json_encode(array('status'=>1,'data'=>$info));

    // }


     //获取汽车品牌列表
    public function carList(){

         $info = Db::name('car')->where('state',1)->field(['id'=>'value','name'=>'label','pid','px'])->order('px')->select();

         $arr = $this->getTree($info);

         //halt($arr);
         echo json_encode(array('status'=>1,'data'=>$arr));

    }



    //获取汽车品牌列表
    public function carList1(){

         $info = Db::name('car')->where('state',1)->where('level',1)->field(['id','name','pid','px','zimu'])->order('px')->select();

         echo json_encode(array('status'=>1,'data'=>$info));

    }



     //获取车型列表
    public function carxhList(){

        $pid = $this->request->param('pid');

         $info = Car::where('level',2)->where('pid',$pid)->where('state',1)->field(['id'=>'value','name'=>'label','pid','px'])->order('px')->select();

         echo json_encode(array('status'=>1,'data'=>$info));

    }


    //计算价格
    public function checkPrice(){

         $sid = input("post.sid");
         $cityid = input("post.cityid");
         $carid = input("post.carid");

         $price = 0.00;

         $sinfo = Service::where('id',$sid)->find();

         $price = $sinfo['price'];

         $cityinfo = City::where('CRI_CODE',$cityid)->find();

         $carinfo = Car::where('id',$carid)->find();


         

         if ($sinfo['id'] == 1) {
                
                if ($sinfo['is_fixed'] == 2) {
             
                     $price = $price + $cityinfo['base'] + $carinfo['base'];
                 }
         }else if ($sinfo['id'] == 2) {
                
                $price = $carinfo['jzpg'];

         }else if ($sinfo['id'] == 3) {
                
                $price = $carinfo['wtc'];

         }else if ($sinfo['id'] == 4) {
                
                $price = $carinfo['gjbw'];
         }

         $price = sprintf("%.2f", $price);

         //halt($arr);
         echo json_encode(array('status'=>1,'data'=>$price));

    }


    //预付定金
    public function deposit(){

         $info = Db::table('yup_set')->where('id',1)->find();

         $info['price'] = sprintf("%.2f", $info['price']);

         //halt($arr);
         echo json_encode(array('status'=>1,'data'=>$info));

    }


    //生成预约订单
    public function createOrder(){

            $info = input("post.");

            unset($info['money']);

            $price = 0.00;

            $sinfo = Service::where('id',$info['sid'])->find();

             $price = $sinfo['price'];

             $cityinfo = City::where('CRI_CODE',$info['county_id'])->find();

             $carinfo = Car::where('id',$info['model_id'])->find();

             
             if ($sinfo['id'] == 1) {
                
                if ($sinfo['is_fixed'] == 2) {
             
                     $price = $price + $cityinfo['base'] + $carinfo['base'];
                 }
             }else if ($sinfo['id'] == 2) {
                    
                    $price = $carinfo['jzpg'];

             }else if ($sinfo['id'] == 3) {
                    
                    $price = $carinfo['wtc'];

             }else if ($sinfo['id'] == 4) {
                    
                    $price = $carinfo['gjbw'];
             }

             $price = sprintf("%.2f", $price);

             $code = $this->getCode();

             $info['price'] = $price;

             $info['deposit'] = Db::table('yup_set')->where('id',1)->find()['price'];

             $info['code'] = $code;

             $orderinfo = Order::create($info);

             $data = Order::where('id',$orderinfo->id)->find();

             echo json_encode(array('status'=>1,'data'=>$data));

    }



    //订单列表
    public function orderList(){

        $uid = input("post.uid");

        $tag = input("post.tag");

        if ($tag == 0) {
            
            $data = Order::with('serviceinfo')->where('uid',$uid)->order('create_time','desc')->select();

        }else{

            $data = Order::with('serviceinfo')->where('uid',$uid)->where('status',$tag)->order('create_time','desc')->select();
        }

        echo json_encode(array('status'=>1,'data'=>$data));

    }




    //员工订单列表
    public function staffOrder(){

        $uid = input("post.uid");

        $tag = input("post.tag");

        if ($tag == 0) {
            
            $data = Order::with('serviceinfo')->where('staff_id',$uid)->order('create_time','desc')->select();

        }else{

            $data = Order::with('serviceinfo')->where('staff_id',$uid)->where('status',$tag)->order('create_time','desc')->select();
        }

        echo json_encode(array('status'=>1,'data'=>$data));

    }





    //生成订单号
    public function getCode() {

        $code = 'ZJJT'.(time()+rand(10000,99999));

        $codeinfo = Order::where('code',$code)->find();

        if ($codeinfo) {
            $this->getCode();
        }else{
            return $code;
        }
    }




    //用户信息
    public function userInfo() {

        $uid = input("post.uid");

        $userinfo = User::where('id',$uid)->find();

        echo json_encode(array('status'=>1,'data'=>$userinfo));

    }




    //授权头像昵称后修改
    public function updateUser() {

        $info = input("post.");

        User::where('id',$info['uid'])->update(['name'=>$info['name'],'img'=>$info['img']]);

        $userinfo = User::where('id',$info['uid'])->find();

        echo json_encode(array('status'=>1,'data'=>$userinfo));

    }




     //检测报告基本信息
    public function reportInfo() {

        $oid = input("post.oid");

        $orderinfo = Order::where('id',$oid)->find();

        $sname = Db::table('yup_service')->where('id',$orderinfo['sid'])->find()['name'];

        if ($orderinfo['status'] == 2 || $orderinfo['status'] == 3) {
            Order::where('id',$oid)->update(['status'=>3]);
        }

        

        $info = Db::table('yup_report')->where('oid',$oid)->find();

        $info['service_name'] = $sname;

        $info['banner'] = json_decode($info['banner']);
        
        $info['images'] = json_decode($info['images'], true);


        $textinfo = Db::table('yup_text')->where('id',1)->find();

        $info['shigu'] = $textinfo['shigu'];
        $info['shuipao'] = $textinfo['shuipao'];
        $info['huoshao'] = $textinfo['huoshao'];
        
        echo json_encode(array('status'=>1,'data'=>$info));
    }



     //存储检测报告基本信息
    public function reportCreate() {

        $info = input("post.");

        $orderinfo = Order::where('id',$info['oid'])->find();

        $info['uid'] =  $orderinfo['uid'];

        $info['staffid'] =  $orderinfo['staff_id'];

        $info['code'] =  $orderinfo['code'];

        $oldinfo = Report::where('oid',$info['oid'])->find();

        if ($oldinfo) {

            Report::where('id',$oldinfo['id'])->update($info);

        }else{

            Report::create($info);
        }

        
        echo json_encode(array('status'=>1,'data'=>'成功'));
    }





    //获取检测项以及名下的异常项
    public function checkList() {

        $oid = input("oid");

        $checkid = input("checkid");

        $orderinfo = Order::where('id',$oid)->find();

        $sid = $orderinfo['sid'];

        //禁用的分类id
        $swids = Db::table('yup_switch')->where('oid',$oid)->field('cid')->column('cid');

        $rinfo = Db::table('yup_report')->where('oid',$oid)->find();

        $swcwhere = [];
        //如果审核已经通过
        if ($rinfo['status'] == 2) {
            
            $swcwhere['id'] = ['not in',$swids];
        }

        $classify = Db::table('yup_classify')->where($swcwhere)->order('px')->select();



        $idarr = Db::table('yup_check')->alias('ck')
                      ->leftJoin('yup_check_service cks','ck.id=cks.cid')
                      ->where('cks.sid',$sid)
                      ->where('ck.state',1)
                      ->order('ck.px')
                      ->field('ck.id')
                      ->column('ck.id');


        //$sids = Db::table('yup_check_service')->where('sid',$sid)->field('cid')->column('cid');

        // $idarr = Db::table('yup_check')->where('id','in',$sids)->where('state',1)->order('px')->field('id')->column('id');
        //halt($sids);


        for ($o=0; $o < count($classify); $o++) { 

                if (in_array($classify[$o]['id'], $swids)) {
                       
                       $classify[$o]['is_show'] = 0; 
                }else{

                      $classify[$o]['is_show'] = 1; 
                }

                if ($o == 0) {
                        
                      $classify[$o]['open'] = 1;

                }else{

                     $classify[$o]['open'] = 0;

                }
                
                $list = Db::table('yup_check')->where('id','in',$idarr)->where('cid',$classify[$o]['id'])->order('px')->select();

                // halt($list);

                //异常的检测项id
                $rids = ReportList::where('oid',$oid)->order('id')->field('cid')->column('cid');

                //不可检状态的检测项ID
                $dids = Db::table('yup_disable')->where('oid',$oid)->order('id')->field('cid')->column('cid');


                //总共检测异常项
                $z_abnormal_num = 0;

                $z_abnormal_num = count($list);

                $yc_abnormal_num = 0;

                for ($i=0; $i < count($list); $i++) { 

                    $list[$i]['abnormal'] = Db::table('yup_abnormal')->where('cid',$list[$i]['id'])->where('state',1)->order('px')->select();

                    
                    $list[$i]['show'] = false;

                    if ($checkid) {
                        
                        if ($list[$i]['id'] == $checkid) {
                            
                            $list[$i]['show'] = true;
                        }
                    }
                    
                    if (in_array($list[$i]['id'], $rids)) {
                         
                         $list[$i]['is_fault'] = 1;
                         $yc_abnormal_num ++;

                         $list[$i]['show'] = true;

                         //异常的检测项
                         // $reinfo = ReportList::where('oid',$oid)->where('cid',$list[$i]['id'])->order('id')->find();

                         $reinfo = Db::table('yup_report_list')->where('oid',$oid)->where('cid',$list[$i]['id'])->order('id')->find();


                         if (!empty($reinfo['aids'])) {

                             $reinfo['aids'] = json_decode($reinfo['aids']);

                             //halt($reinfo['aids']);

                         }else{

                            $reinfo['aids'] = [];
                         }



                         if ($reinfo['imgs']) {

                             $reinfo['imgs'] = json_decode($reinfo['imgs']);

                         }else{

                            $reinfo['imgs'] = [];
                         }


                         $list[$i]['fault_imgs'] = $reinfo['imgs'];



                         for ($k=0; $k < count($list[$i]['abnormal']); $k++) { 

                            if (isset($list[$i]['abnormal'][$k]['id'])) {

                                 if (in_array($list[$i]['abnormal'][$k]['id'],$reinfo['aids'])) {
                                    
                                        $list[$i]['abnormal'][$k]['is_fault'] = 1;

                                        
                                 }else{

                                        $list[$i]['abnormal'][$k]['is_fault'] = 0;
                                 }
                            }else{
                                $list[$i]['abnormal'][$k]['is_fault'] = 0;
                            }

                             //halt($list[$i]['abnormal'][$k]['id']);
                             
                         }

                    }else{

                         $list[$i]['is_fault'] = 0;

                    }


                    if (in_array($list[$i]['id'], $dids)){

                        $list[$i]['is_fault'] = 2;
                    }
                }


                $classify[$o]['list'] = $list;

                $classify[$o]['z_abnormal_num'] = $z_abnormal_num;

                $classify[$o]['yc_abnormal_num'] = $yc_abnormal_num;

        }
                      
        



        //halt($list);

        

        

        echo json_encode(array('status'=>1,'data'=>$classify));

    }




     //检测项提交
     // public function tjcheck() {

     //    $oid = input("post.oid");

     //    $checkid = input("post.checkid");

     //    $is_fault = input("post.is_fault");

     //    $info = Report::where('oid',$oid)->find();

     //    $listinfo = ReportList::where('oid',$oid)->where('cid',$checkid)->find();

     //    if ($is_fault == 0) {

     //        if ($listinfo) {
     //            ReportList::where('id',$listinfo['id'])->delete();
     //        }

     //    }else if ($is_fault == 1) {
            
     //        if (!$listinfo) {
     //            ReportList::create(['oid'=>$oid,'cid'=>$checkid,'rid'=>$info['id'],'create_time'=>date('Y-m-d H:i:s')]);
     //        }
     //    }

     //    echo json_encode(array('status'=>1,'data'=>'成功'));

     // }



      //异常项提交
     public function tjyichang() {

        $oid = input("post.oid");

        $checkid = input("post.checkid");

        $abnormal_id = input("post.abnormal_id");

        $is_fault = input("post.is_fault");

        $info = Report::where('oid',$oid)->find();

        $listinfo = ReportList::where('oid',$oid)->where('cid',$checkid)->find();


        $add_aids = [];
        $json_aids = "";

        if ($is_fault == 0) {

            if ($listinfo) {
                
                 $aids = $listinfo['aids'];

                 $key = array_search($abnormal_id,$aids);

                 if ($key || $key == 0) {
                        
                     unset($aids[$key]);

                     $aids = array_values($aids);

                     $json_aids = json_encode($aids);
                 }


                 //如果没有异常项了  删掉记录
                 if (count($aids) == 0) {

                      ReportList::where('id',$listinfo['id'])->delete();

                      echo json_encode(array('status'=>1,'data'=>'成功'));
                      exit();
                 }
                 
            }

        }else if ($is_fault == 1) {
            
            if ($listinfo) {

                //halt($listinfo);
                
                if (!empty($listinfo['aids'])) {
                    $aids = $listinfo['aids'];
                }else{
                    $aids = [];
                }
                 
                if (!in_array($abnormal_id, $aids)) {
                        
                    //halt($aids);
                     $key = array_search($abnormal_id,$aids);


                     if (!$key) {
                            
                        array_push($aids, $abnormal_id);

                        $aids = array_values($aids);

                        

                     }   

                }

                 $json_aids = json_encode($aids);

            }else{

                array_push($add_aids, $abnormal_id);

                $add_aids = array_values($add_aids);

                $json_aids = json_encode($add_aids);


                ReportList::create(['oid'=>$oid,'cid'=>$checkid,'rid'=>$info['id'],'create_time'=>date('Y-m-d H:i:s'),'aids'=>$json_aids]);

                echo json_encode(array('status'=>1,'data'=>'成功'));
                exit();
            }
            
        }


        ReportList::where('id',$listinfo['id'])->update(['aids'=>$json_aids]);

        echo json_encode(array('status'=>1,'data'=>'成功'));
        exit();

        

     }







    //图片上传
     public function uploadImg() {

        $oid = input("post.oid");

        $checkid = input("post.checkid");

        $imgpath = input("post.imgpath");

        $listinfo = ReportList::where('oid',$oid)->where('cid',$checkid)->find();


        if ($listinfo) {

            if (!empty($listinfo['imgs'])) {
                 $imgs = $listinfo['imgs'];
            }else{
                 $imgs = [];
            }

             array_push($imgs,$imgpath);

             $imgs = json_encode($imgs);

             ReportList::where('id',$listinfo['id'])->update(['imgs'=>$imgs]);
             
        }


        echo json_encode(array('status'=>1,'data'=>'成功'));
        exit();

        

     }





     //图片删除
     public function deleteImg() {

        $oid = input("post.oid");

        $checkid = input("post.checkid");

        $key = input("post.key");

        $listinfo = ReportList::where('oid',$oid)->where('cid',$checkid)->find();


        if ($listinfo) {

            if (!empty($listinfo['imgs'])) {
                 $imgs = $listinfo['imgs'];
            }else{
                 $imgs = [];
            }

             unset($imgs[$key]);

             $imgs = array_values($imgs);

             $imgs = json_encode($imgs);

             ReportList::where('id',$listinfo['id'])->update(['imgs'=>$imgs]);
             
        }


        echo json_encode(array('status'=>1,'data'=>'成功'));
        exit();
     }








     //提交检测报告  审核中
     public function submit(){

        $oid = input("post.oid");

        $info = Report::where('oid',$oid)->find();

        if ($info) {
            
            Report::where('id',$info['id'])->update(['status'=>1]);
        }


        echo json_encode(array('status'=>1,'data'=>'成功'));
        exit();


     }





    //轮播图上传
    public function uploadBanner() {

        $oid = input("post.oid");

        $imgpath = input("post.imgpath");

        $listinfo = Report::where('oid',$oid)->find();


        if ($listinfo) {

            if (!empty($listinfo['banner'])) {

                 $listinfo['banner'] = json_decode($listinfo['banner']);
                 $imgs = $listinfo['banner'];
            }else{
                 $imgs = [];
            }

             array_push($imgs,$imgpath);

             $imgs = json_encode($imgs);

             Report::where('id',$listinfo['id'])->update(['banner'=>$imgs]);
             
        }

        echo json_encode(array('status'=>1,'data'=>'成功'));
        exit();

        

    }
    
    //车辆图片上传
    public function changeCarImg() {
        $oid = input("post.oid");
        $imgpath = input("post.imgpath");
        $index = input('post.index');
        $listinfo = Report::where('oid',$oid)->find();
        if(!$listinfo) return json(['code'=>1, 'msg'=>'报告不存在']);
        if($index !== ''){
            $imgs = json_decode($listinfo['images'] , true);
            $imgs = is_array($imgs) ? $imgs : [];
            // 数组
            foreach($this->img_text as $k=>$text){
                if($index == $k){
                    $imgs[$k] = $imgpath ? : null;
                }
                $imgs[$k] = array_key_exists($k, $imgs) ? $imgs[$k] : null;
            }
            Report::where('id',$listinfo['id'])->update(['images'=>json_encode($imgs)]);
        }
        return json(['code'=>0]);
    }





     //图片删除
     public function deleteBanner() {

        $oid = input("post.oid");

        $key = input("post.key");

        $listinfo = Report::where('oid',$oid)->find();


        if ($listinfo) {

            if (!empty($listinfo['banner'])) {

                 $listinfo['banner'] = json_decode($listinfo['banner']);

                 $imgs = $listinfo['banner'];
            }else{
                 $imgs = [];
            }

             unset($imgs[$key]);

             $imgs = array_values($imgs);

             $imgs = json_encode($imgs);

             Report::where('id',$listinfo['id'])->update(['banner'=>$imgs]);
             
        }


        echo json_encode(array('status'=>1,'data'=>'成功'));
        exit();
     }



     //开关  启用禁用
     public function switch(){

        $oid = input("post.oid");

        //十大类的ID
        $cid = input("post.cid");

        //1是开  0是关
        $status = input("post.status");

        $info = Db::table('yup_switch')->where('oid',$oid)->where('cid',$cid)->find();

        //如果禁用
        if ($status == 1) {
            
            if (!$info) {
                
                Db::table('yup_switch')->insert(['oid'=>$oid,'cid'=>$cid]);
            }
        }else{

             if ($info) {
                
                Db::table('yup_switch')->where('id',$info['id'])->delete();
            }
        }


         echo json_encode(array('status'=>1,'data'=>'成功'));
         exit();


     }




       //检测项变更为不可检状态
     public function disable(){

        $oid = input("post.oid");

        //检测项ID
        $cid = input("post.cid");

        //1不可检   0取消不可检
        $status = input("post.status");

        $info = Db::table('yup_disable')->where('oid',$oid)->where('cid',$cid)->find();

        //如果不可检
        if ($status == 1) {
            
            if (!$info) {
                
                Db::table('yup_disable')->insert(['oid'=>$oid,'cid'=>$cid]);
            }
        }else{

             if ($info) {
                
                Db::table('yup_disable')->where('id',$info['id'])->delete();
            }
        }


         echo json_encode(array('status'=>1,'data'=>'成功'));
         exit();


     }




      //检测报告页眉信息
     public function yemei(){

         $info = Db::table('yup_set')->where('id',1)->find()['header'];

         echo json_encode(array('status'=>1,'data'=>$info));
         exit();


     }
    // 图片文字
    public function imgtext(){
        return json(['status'=>1, 'data'=>$this->img_text]);
    }
  
    //事故水泡火烧文本介绍
     public function text(){

         $info = Db::table('yup_text')->where('id',1)->find();

         echo json_encode(array('status'=>1,'data'=>$info));
         exit();


     }





    



}